package com.qf.shiro;


import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.qf.service.FilterChainService;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

@Configuration
public class shiroConfig {

    //thymeleaf整合shiro 配置
    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }

    //将自定义realm放入spring容器中
    @Bean
    public Realm realm(){
        return new DevCustomRealm();
    }
    //需要在spring容器中创建两个实例分别为：
    // SecurityManager              ShiroFilterChainDefinition
    //安全管理器放自定义realm对象       过滤器链存放对象  将过滤器链一个一个add||直接add map集合
    @Bean
    public DefaultWebSecurityManager securityManager(Realm realm,AppSessionDAO appSessionDAO){

        //1. 创建安全管理器
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //2. 注入realm
        securityManager.setRealm(realm);
        //3. 创建SessionManager.
        AppSessionManager sessionManager = new AppSessionManager();

        //4. 将SessionDAO注入到SessionManager
        sessionManager.setSessionDAO(appSessionDAO);

        //5. 设置给securityManager
        securityManager.setSessionManager(sessionManager);

        //6. 返回安全管理器对象
        return securityManager;
    }

    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition(FilterChainService filterChainService){
        //创建过滤器链对象用于存储过滤器链
        DefaultShiroFilterChainDefinition filterchain = new DefaultShiroFilterChainDefinition();
        //从数据库中查询出过滤器链信息并放入map集合中
        LinkedHashMap<String,String> map = filterChainService.findShiroFilterChain();
        //将查询到的结果add到该对象中
        filterchain.addPathDefinitions(map);
        //返回过滤器链对象
        return filterchain;
    }

}
